﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Xml;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Timers;


namespace NativeBayes
{
    public partial class Sample : Form
    {
        const string path = @"ICTCLAS2011.dll";
        System.Timers.Timer t = new System.Timers.Timer(10000);         //实例化Timer类，设置间隔时间为30000毫秒（30秒）
  
        [DllImport(path, CharSet = CharSet.Ansi, EntryPoint = "ICTCLAS_Init")]
        public static extern bool ICTCLAS_Init(String sInitDirPath);

        [DllImport(path, CharSet = CharSet.Ansi, EntryPoint = "ICTCLAS_ParagraphProcess")]
        public static extern String ICTCLAS_ParagraphProcess(String sParagraph, int bPOStagged);

        [DllImport(path, CharSet = CharSet.Ansi, EntryPoint = "ICTCLAS_Exit")]
        public static extern bool ICTCLAS_Exit();

        [DllImport(path, CharSet = CharSet.Ansi, EntryPoint = "ICTCLAS_ImportUserDict")]
        public static extern int ICTCLAS_ImportUserDict(String sFilename);

        [DllImport(path, CharSet = CharSet.Ansi, EntryPoint = "ICTCLAS_GetParagraphProcessAWordCount")]
        static extern int ICTCLAS_GetParagraphProcessAWordCount(String sParagraph);
        //ICTCLAS_GetParagraphProcessAWordCount
        [DllImport(path, CharSet = CharSet.Ansi, EntryPoint = "ICTCLAS_ParagraphProcessAW")]
        static extern void ICTCLAS_ParagraphProcessAW(int nCount, [Out, MarshalAs(UnmanagedType.LPArray)] result_t[] result);

        oAuthSina oauth = new oAuthSina();
        static DB db = new DB("tweet.db");                                  //连接数据库
        long sinceID = 9710471237;
        Classifier cl = new Classifier();

        //static Dictionary<string, long[]> fc = new Dictionary<string,long[]>() ;
        //static long[] cc = new long[2];
        
        //List<string> segment = new List<string>();
 
        public Sample()
        {
            InitializeComponent();
           // string[] strArr = new string[6] { "public_timeline", "friends_timeline", "user_timeline", "mentions", "comments_timeline", "comments_by_me" };
            //this.methodsComboBox.DataSource = strArr;
            dataGridView1.ColumnCount = 3;                    //初始化dataGridView
            dataGridView1.Columns[0].Name = "作者";
            dataGridView1.Columns[1].Name = "内容";
            dataGridView1.Columns[2].Name = "概率"; 
            sinceID = db.GetSinceID();

        }

        public static bool IsChinese(string inString)
        {
            Regex regex = new Regex("[^\u4e00-\u9fa5]");
            return regex.IsMatch(inString.Trim());
        }

        private void GetAuthlink_Click_1(object sender, EventArgs e)
        {

            oauth.RequestTokenGet();
            //this.SinaAuthLink.Text = oauth.AuthorizationGet();
            Process ieProc = Process.Start("IExplore.exe", oauth.AuthorizationGet());  //打开IE浏览器进入oauth认证页面
        }

        private void GetAccessToken_Click(object sender, EventArgs e)
        {
            oauth.Verifier = this.pinBox.Text.Trim();

            oauth.AccessTokenGet();
        }

        private void invoke_Click(object sender, EventArgs e)
        {
           
            
            t.Elapsed += new System.Timers.ElapsedEventHandler(theout);     //到达时间的时候执行事件； 
            t.AutoReset = true;                                             //设置是执行一次（false）还是一直执行(true)； 
            t.Enabled = true;                                               //是否执行System.Timers.Timer.Elapsed事件；

            // 更新微博       
            /*
                   private void Update_Click(object sender, EventArgs e)
                   {
                       string url = "http://api.t.sina.com.cn/statuses/update.xml?";
                       this.resultTextBox2.Text = oauth.oAuthWebRequest(oAuthSina.Method.POST, url, "status=" + HttpUtility.UrlEncode(statusText.Text));
                   }

                   private void Upload_Click(object sender, EventArgs e)
                   {
                       string url = "http://api.t.sina.com.cn/statuses/upload.xml?";
                       this.resultTextBox2.Text = oauth.oAuthWebRequestWithPic(oAuthSina.Method.POST, url, "status=" + HttpUtility.UrlEncode(statusText.Text), filepath.Text);
                   }
           */
        }

        public void theout(object source, System.Timers.ElapsedEventArgs e)
        {
            string basic = "http://api.t.sina.com.cn/";
            string url = "";
  
            url = basic + "statuses/friends_timeline.xml?since_id="+sinceID.ToString();
           // url = basic + "statuses/friends_timeline.xml" ;
            string res = "";
            res = oauth.oAuthWebRequest(oAuthSina.Method.GET, url, String.Empty); 

            string createtime = "";                  //微博时间
            string content = "";                     //微博内容
            string username = "";                    //微博作者
            long nowID = 0;
            // Regex reg = new Regex(@"[^\w]");
            //Regex reg = new Regex(@"[^\u4e00-\u9fa5]");  //只保留中文

            //dataGridView1.ColumnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.True;

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(res);
            XmlNodeList topM = doc.DocumentElement.ChildNodes;



            ICTCLAS_ImportUserDict("userdic.txt");

            foreach (XmlElement element in topM)
            {
                if (element.Name.ToLower() == "status")
                {
                    XmlNodeList nodelist = element.ChildNodes;
                    content = "";
                    username = "";
                    //得到该节点的子节点 
                    foreach (XmlElement el in nodelist)//读元素值
                    {
                        if (el.Name == "created_at")
                        {
                            createtime = el.InnerText;                     //读取微博时间
                        }

                        if (el.Name == "id")
                        {
                            nowID = Convert.ToInt64(el.InnerText);
                            if (nowID > sinceID)
                                sinceID = nowID + 1;
                        }

                        if (el.Name == "text")
                        {
                            content += el.InnerText;                        //读取微博内容

                        }
                        
                        if (el.Name == "user")                            //读取作者名
                        {
                            foreach (XmlElement users in el)
                            {
                                if (users.Name == "screen_name")
                                {
                                    username = users.InnerText;
                                }
                            }
                        }

                        if (el.Name == "retweeted_status")                            //读取作者名
                        {
                            string retweet_name = "" ;
                            string retweet_text = "" ;
                            //int flag = 0;
                            foreach (XmlElement text in el)
                            {
                                if (text.Name == "text")
                                {
                                    retweet_text = text.InnerText;
                                    //content += "  RT @" + retweet_name + ": " + retweet_text;
                                    content += " RT @" + retweet_name + ": " + retweet_text;
                                    break;

                                }
                                /*
                                if (text.Name == "user")                            //读取作者名
                                {
                                    foreach (XmlElement rename in text)
                                    {
                                        if (rename.Name == "screen_name")
                                        {
                                            //content += " RT @" + rename.InnerText;
                                            retweet_name = rename.InnerText;
                                            content += " RT @" + retweet_name + ": " + retweet_text;
                                        }
                                    }
                                   
                                }*/

/*
                                if (!retweet_text.Equals("") && !retweet_name.Equals(""))
                                {
                                   
                                    break;
                                }*/
                            }
              
                        }

                    }

                    //string[] str = { username, segment };
                    //List<string> segment = getWord(content);
                    //segment.Add(username);                     //将作者名作为特征之一
                    //double prob = cl.prob(segment , 0);
                    double prob = 0.0;
                    
                    string[] str = { username, content ,prob.ToString()};
                    //string[] str = { nowID.ToString(), content};
                    this.Invoke((MethodInvoker)delegate
                    {
                            dataGridView1.Rows.Add(str);           //显示数据
                    });
                    //db.Add(nowID, createtime, username, content);  //将数据写入数据库

                }
                db.SetSinceID(sinceID);                             //写入sinceID至数据库
                // ICTCLAS_Exit();

            }
        }


        //////////////// 分词 ////////////////////
        private List<String> getWord( string content )
        {
            /*初始化分词器*/
            if (!ICTCLAS_Init(null))
            {
                System.Console.WriteLine("Init ICTCLAS failed!");
                return new List<string>();
            }
            List<string> segment = new List<string>();
            Regex reg = new Regex(@"[^\u4e00-\u9fa5]");  //只保留中文

            string ans = reg.Replace(content, "");                   //去除所有符号
            int count = ICTCLAS_GetParagraphProcessAWordCount(ans);  //先得到结果的词数
            result_t[] result = new result_t[count];                 //在客户端申请资源
            ICTCLAS_ParagraphProcessAW(count, result);               //获取结果存到客户的内存中
            foreach (result_t r in result)
            {
                segment.Add(ans.Substring(r.start / 2, r.length / 2));

            }
            return segment;
        }
        
        //停止更新
        private void button1_Click(object sender, EventArgs e)
        {
            //db.ExecuteQuery("CREATE TABLE [info] (id INTEGER , username TEXT , created_at TEXT , text TEXT)");
            t.Enabled = false;                                               //关闭定时器

            //string[] str = {"邓淼江","这个游泳池很适合我",""};
            //dataGridView1.Rows.Add(str);
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            
            List<string> segment = getWord(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());  //对微博内容进行分词
            segment.Add(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());                     //将作者名作为特征之一
            
            //List<string> segment = getWord("这个游泳池很适合我.");  
            cl.train(segment, 0);
            
        }

        private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            
            if (e.Button != MouseButtons.Right || e.RowIndex < 0)
                return;
            
            dataGridView1.Rows[e.RowIndex].Selected = true;
            List<string> segment = getWord(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());  //对微博内容进行分词
            segment.Add(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());                     //将作者名作为特征之一
            cl.train(segment, 1);
           
            //dataGridView1.Rows[e.RowIndex].Selected = false;
            //MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());
             
        }

        private void Sample_FormClosing(object sender, FormClosingEventArgs e)
        {
            t.Enabled = false;
           // db.Updatecc(cc);
           // db.Updatefc(fc);
            cl.SaveData();
        }
 
    }
}
